﻿using System;
using System.Collections.Generic;
using System.Text;

namespace KelonProud
{
    public static class ObjectExtensions
    {
        public static T ToConvertOrDefault<T>(this object obj, T defaultValue)
        {
            try
            {
                return (T)Convert.ChangeType(obj, typeof(T));
            }
            catch
            {
                return defaultValue;
            }
        }

        public static DateTime ToDateTime(this object obj, DateTime defaultValue)
        {
            if (obj == null)
                return defaultValue;
            DateTime result;

            if (DateTime.TryParse(obj.ToString(), out result))
                return result;

            return defaultValue;
        }

        public static double ToDouble(this object obj, double defaultValue = 0)
        {
            if (obj == null)
                return defaultValue;
            double result;

            if (Double.TryParse(obj.ToString(), out result))
                return result;

            return defaultValue;
        }

        public static int ToInt32(this object obj, int defaultValue = 0)
        {
            if (obj == null)
                return defaultValue;
            int result;

            if (int.TryParse(obj.ToString(), out result))
                return result;

            return defaultValue;
        }

        public static short ToInt16(this object obj, short defaultValue = 0)
        {
            if (obj == null)
                return defaultValue;

            return short.TryParse(obj.ToString(), out short result) ? result : defaultValue;
        }

        public static double ToTenThousand(this object obj, int defaultValue = 0)
        {
            if (obj == null)
                return defaultValue;
            double result;
            if (double.TryParse(obj.ToString(), out result))
            {
                return result / 10000;
            }
            return defaultValue;
        }

        public static T ToEnum<T>(this object value)
        {
            return (T)Enum.Parse(typeof(T), value.ToString());
        }

        internal static object ToDateTime(DateTime? dateTime)
        {
            throw new NotImplementedException();
        }
    }
}
